import java.applet.*;
import java.awt.*;
import java.io.*;
import com.lowagie.text.DocumentException;
import org.xhtmlrenderer.pdf.ITextRenderer;
import netscape.javascript.JSObject;
import java.security.AccessController;
import java.security.*;  
import org.w3c.tidy.Tidy;

// The applet's class name must be identical to the filename.
public class PDFPrinter extends Applet {
   JSObject jso;
   FileHandler fileHandler;

   // This gets executed when the applet starts.
   public void init() {
      //jso = JSObject.getWindow(this);
   }

   public void printPDF(String msg){
      try{
        msg = msg.replace("<html>", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\">");
        msg = msg.replace("<head>", "<head><style>@page { size: 210mm 297mm; margin: 10mm; } .divPageBreaker{ display: none; } </style>");
        
        StringReader reader = new StringReader(msg);
        StringWriter writer = new StringWriter();
        Tidy tidy = new Tidy();
        tidy.setXHTML(true);
        tidy.parse(reader, writer);
        
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(writer.toString());
        renderer.layout();
        renderer.createPDF(os);
        FileHandler.save(os.toByteArray(), "file.pdf", "pdf");

        os.close();
        reader.close();
        writer.close();
      }catch(Exception ex){
        jso.call("tryAlert", new String[] {ex.getMessage()});
      }
   }
   
   public void save(String msg){
      try{
        StringReader reader = new StringReader(msg);
        
        FileHandler.save(msg.getBytes(), "file.html", "html");

        reader.close();
      }catch(Exception ex){
        jso.call("tryAlert", new String[] {ex.getMessage()});
      }
   }
   
   public String open(){
      try{
        return FileHandler.open();
      }catch(Exception ex){
        jso.call("tryAlert", new String[] {ex.getMessage()});
      }

      return null;
   }

   public void destroy(){
      System.exit(1);	
   }
}
